package com.shop.cereshop.app.tencent.im.callback.impl;

import com.shop.cereshop.app.tencent.im.callback.TimCallbackHandler;
import com.shop.cereshop.commons.tencent.im.model.callback.request.AfterMsgWithdrawCallbackRequest;
import com.shop.cereshop.commons.tencent.im.model.callback.response.CallbackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.shop.cereshop.commons.tencent.im.constant.CallbackCommand.C2C_CALLBACK_AFTER_MSG_WITHDRAW;

/**
 * @description: 发单聊消息撤回后回调处理器,处理 C2C.CallbackAfterMsgWithDraw
 * @author zdd
 * @date 2025/9/11 10:29
 * @version 1.0
 */
@Slf4j
@Service
public class AfterMsgWithdrawCallbackImpl implements TimCallbackHandler<AfterMsgWithdrawCallbackRequest> {

    @Override
    public String getCommand() {
        return C2C_CALLBACK_AFTER_MSG_WITHDRAW;
    }

    @Override
    public CallbackResponse handle(AfterMsgWithdrawCallbackRequest request) {
        log.info("Processing AfterMsgWithdraw callback: From={}, To={}, MsgKey={}, EventTime={}",
                request.getFromAccount(), request.getToAccount(), request.getMsgKey(), request.getEventTime());
        try {
//            // 记录撤回日志
//            logWithdraw(request);
//
//            // 从您的日志或数据库中删除或标记该消息为已撤回
//            //    注意：MsgKey 是唯一标识，可用于查找之前记录的消息
//            markMessageAsWithdrawn(request);
//
//            // 通知相关系统消息已撤回 (可选)
//            // notifySystemsOfWithdrawal(request);

            // 处理成功
//            response.setActionStatus("OK");
//            response.setErrorCode(0);
//            response.setErrorInfo("");

            log.info("处理发单聊消息撤回后回调成功, MsgKey: {}", request.getMsgKey());
            return CallbackResponse.success();

        } catch (Exception e) {
            log.error("处理发单聊消息撤回后回调异常, MsgKey: " + request.getMsgKey(), e);
            // 返回失败应答
//            response.setActionStatus("FAIL");
//            response.setErrorCode(1);
//            response.setErrorInfo("Internal server error: " + e.getMessage());
            return CallbackResponse.error("Internal server error: " + e.getMessage());
        }

    }

    /**
     * 记录撤回操作
     */
    private void logWithdraw(AfterMsgWithdrawCallbackRequest request) {
        log.debug("记录消息撤回: {}", request);
        // writeToAuditLog(request);
    }

    /**
     * 标记消息为已撤回
     * 根据 MsgKey 查找并更新您存储的消息状态
     */
    private void markMessageAsWithdrawn(AfterMsgWithdrawCallbackRequest request) {
        // 示例：更新数据库
        // messageLogService.updateMessageStatus(request.getMsgKey(), "WITHDRAWN");
        log.debug("在存储中将邮件标记为已撤回, MsgKey: {}", request.getMsgKey());
    }

    /**
     * 通知其他系统
     */
    // private void notifySystemsOfWithdrawal(AfterMsgWithdrawCallbackRequest request) {
    //     // 例如，发送消息到 MQ，通知聊天记录服务删除缓存等
    //     messageQueueProducer.sendWithdrawalEvent(request);
    // }



}
